// Dify API 配置
const DIFY_BASE_URL = 'http://10.81.129.79';
const DIFY_API_KEY = 'app-495q4rS1atfZKg8m1RrgsoFx';

export async function weeklyDeliveryStrategyChat(params: {
  query: string;
  conversation_id?: string;
  user?: string;
  onMessage?: (message: string) => void;
  onError?: (error: Error) => void;
  onComplete?: () => void;
}) {
  const { query, conversation_id, user, onMessage, onError, onComplete } = params;
  try {
    const requestBody = {
      inputs: {},
      query,
      response_mode: 'streaming',
      conversation_id: conversation_id || undefined,
      user: user || 'user',
    };
    const response = await fetch(`${DIFY_BASE_URL}/v1/chat-messages`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${DIFY_API_KEY}`,
      },
      body: JSON.stringify(requestBody),
    });
    if (!response.ok) {
      const errorText = await response.text();
      throw new Error(`HTTP error! status: ${response.status}, message: ${errorText}`);
    }
    const reader = response.body?.getReader();
    if (!reader) throw new Error('Response body is not readable');
    const decoder = new TextDecoder();
    let buffer = '';
    let fullResponse = '';
    let conversationId = conversation_id;
    let hasReceivedData = false;

    while (true) {
      const { done, value } = await reader.read();
      if (done) {
        // 流结束时触发完成回调
        onComplete?.();
        break;
      }
      buffer += decoder.decode(value, { stream: true });
      const lines = buffer.split('\n');
      buffer = lines.pop() || '';
      for (const line of lines) {
        if (!line.trim()) continue;
        if (line.startsWith('data: ')) {
          const data = line.slice(6).trim();
          if (data === '[DONE]' || data === '') continue;
          try {
            const json = JSON.parse(data);
            if (json.event) {
              if (
                json.event === 'message' ||
                json.event === 'message_chunk' ||
                json.event === 'message_file' ||
                json.event === 'agent_message'
              ) {
                const answerText = json.answer || json.text || json.content || '';
                if (answerText) {
                  if (json.event === 'message_chunk') {
                    fullResponse += answerText;
                    hasReceivedData = true;
                  } else {
                    if (!fullResponse || answerText.length >= fullResponse.length) {
                      fullResponse = answerText;
                      hasReceivedData = true;
                    }
                  }
                  if (hasReceivedData) onMessage?.(fullResponse);
                }
                if (json.conversation_id && !conversationId) {
                  conversationId = json.conversation_id;
                }
              } else if (json.event === 'message_end') {
                if (json.conversation_id && !conversationId) {
                  conversationId = json.conversation_id;
                }
                // 触发完成回调
                onComplete?.();
                if (fullResponse) onMessage?.(fullResponse);
              } else if (json.event === 'error') {
                const errorMsg = json.message || json.error || 'Unknown error';
                throw new Error(errorMsg);
              }
            } else {
              if (json.answer || json.text || json.content) {
                const answerText = json.answer || json.text || json.content;
                if (fullResponse && answerText.length > fullResponse.length) {
                  const newPart = answerText.substring(fullResponse.length);
                  fullResponse += newPart || answerText;
                } else if (!fullResponse) {
                  fullResponse = answerText;
                } else {
                  fullResponse += answerText;
                }
                hasReceivedData = true;
                onMessage?.(fullResponse);
              }
              if (json.conversation_id && !conversationId) {
                conversationId = json.conversation_id;
              }
            }
          } catch (_) {
            if (data && !data.startsWith('{')) {
              fullResponse += data;
              hasReceivedData = true;
              onMessage?.(fullResponse);
            }
          }
        }
      }
    }
    if (buffer.trim()) {
      if (buffer.startsWith('data: ')) {
        const data = buffer.slice(6).trim();
        if (data !== '[DONE]' && data) {
          try {
            const json = JSON.parse(data);
            if (json.answer || json.text || json.content) {
              const answerText: string = json.answer || json.text || json.content;
              fullResponse += answerText;
              hasReceivedData = true;
              onMessage?.(fullResponse);
            }
            if (json.conversation_id && !conversationId) {
              conversationId = json.conversation_id;
            }
          } catch (_) {}
        }
      }
    }
    return { conversation_id: conversationId || conversation_id || undefined, answer: fullResponse };
  } catch (error) {
    const err = error instanceof Error ? error : new Error('Unknown error');
    onError?.(err);
    throw err;
  }
}

